<template>
  <el-dialog
    :append-to-body="true"
    :close-on-click-modal="false"
    :visible="dialogVisible"
    title="发送测试"
    width="600px"
    @close="$emit('closeSend')"
  >
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" class="demo-ruleForm" label-width="120px">
      <el-form-item label="发送人员：" prop="userIdList">
        <el-select
          v-model="ruleForm.userIdList"
          filterable
          multiple
          placeholder="请选择"
          size="small"
          style="width: 100%"
        >
          <el-option
            v-for="(item, index) in personList"
            :key="index"
            :label="item.userName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="['notice', 'email', 'feishu_robot'].includes(sendWay)" prop="title">
        <template #label>
          发送标题
          <el-popover
            content='短信模板变量对应的实际值。支持传入多个参数,示例:{"name":"张三","number":"139000******"}。'
            placement="top-start"
            title="描述"
            trigger="hover"
            width="300"
          >
            <i slot="reference" class="icon el-icon-question"></i>
          </el-popover>
          ：
        </template>
        <el-input v-model="ruleForm.title" size="small"></el-input>
        <div class="form-help">{{ templateData.title }}</div>
      </el-form-item>
      <el-form-item v-if="['notice', 'email', 'sms', 'feishu_robot'].includes(sendWay)" prop="content">
        <template #label>
          发送内容
          <el-popover
            content='短信模板变量对应的实际值。支持传入多个参数,示例:{"name":"张三","number":"139000******"}。'
            placement="top-start"
            title="描述"
            trigger="hover"
            width="300"
          >
            <i slot="reference" class="icon el-icon-question"></i>
          </el-popover>
          ：
        </template>
        <el-input v-model="ruleForm.content" size="small"></el-input>
        <div class="form-help">{{ templateData.content }}</div>
      </el-form-item>
      <el-form-item v-if="['notice'].includes(sendWay)" prop="dealLink">
        <template #label>
          处理链接
          <el-popover
            content='短信模板变量对应的实际值。支持传入多个参数,示例:{"name":"张三","number":"139000******"}。'
            placement="top-start"
            title="描述"
            trigger="hover"
            width="300"
          >
            <i slot="reference" class="icon el-icon-question"></i>
          </el-popover>
        </template>
        ：
        <el-input v-model="ruleForm.dealLink" size="small"></el-input>
        <div class="form-help">{{ templateData.dealLink || '-' }}</div>
      </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button size="small" @click="$emit('closeSend')">取 消</el-button>
      <el-button :loading="loading" size="small" type="primary" @click="handleConfirm">确 认</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { sendTestMessage } from '@/api'
// import { requestUserList } from '@/api/organization'

export default {
  name: 'TestSend',
  components: {},
  props: {
    dialogVisible: {
      type: Boolean,
      default: false,
    },
    sendWay: {
      type: String,
      default: 'notice',
    },
    form: {
      type: Object,
      default: () => {
        return {}
      },
    },
    templateData: {
      type: Object,
      default: () => {
        return {}
      },
    },
  },
  data() {
    return {
      loading: false,
      ruleForm: {
        userIdList: [],
        title: '',
        content: '',
        dealLink: '',
      },
      personList: [],
      rules: {
        userIdList: [{ required: true, type: 'array', minLength: 1, message: '请选择接收人', trigger: 'change' }],
        title: [
          { required: true, message: '请输入发送标题', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (!this.isJSON(value)) {
                return callback(new Error('请输入正确格式'))
              }
              callback()
            },
            trigger: 'blur',
          },
        ],
        content: [
          { required: true, message: '请输入发送内容', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (!this.isJSON(value)) {
                return callback(new Error('请输入正确格式'))
              }
              callback()
            },
            trigger: 'blur',
          },
        ],
        dealLink: [
          // { required: true, message: '请输入处理链接', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback()
              } else if (!this.isJSON(value)) {
                return callback(new Error('请输入正确格式'))
              }
              callback()
            },
            trigger: 'blur',
          },
        ],
      },
    }
  },
  created() {
    // this.getPersonList()
  },
  methods: {
    async getPersonList() {
      const { success, message, data } = await requestUserList({ deleted: false })
      if (success) {
        this.personList = data
      } else {
        this.$message.error(message)
      }
    },
    checkForm() {
      return new Promise((resolve) => {
        this.$refs.ruleForm.validate((valid) => {
          resolve(valid)
        })
      })
    },
    async handleConfirm() {
      if (this.loading) return
      const pass = await this.checkForm()
      if (!pass) return
      this.loading = true
      const { data, success, message } = await sendTestMessage({
        userIdList: this.ruleForm.userIdList,
        title: this.ruleForm.title ? JSON.parse(this.ruleForm.title) : {},
        content: this.ruleForm.content ? JSON.parse(this.ruleForm.content) : {},
        dealLink: this.ruleForm.dealLink ? JSON.parse(this.ruleForm.dealLink) : {},
        feishuAppId: this.form?.sendParamConfig?.feishuAppId ?? '',
        feishuAppSecret: this.form?.sendParamConfig?.feishuAppSecret ?? '',
        configCode: this.form.configCode,
        configName: this.form.configName,
        noticeTypeId: this.form.noticeTypeId,
        templateId: this.form.templateId,
      })
      if (success) {
        this.$message.success('操作成功')
        this.ruleForm = {
          userIdList: [],
          title: '',
          content: '',
          dealLink: '',
        }
        this.loading = false
        this.$emit('closeSend')
      } else {
        this.$message.error(message)
        this.loading = false
      }
    },
    isJSON(str) {
      try {
        if (typeof JSON.parse(str) == 'object') {
          return true
        }
      } catch (e) {}
      return false
    },
  },
}
</script>

<style lang="scss" scoped>
.form-help {
  line-height: 1;
}
</style>
